﻿//-----------------------------------------------------------------------
// <copyright file="ShelveDelete.cs" company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Internal.TeamFoundationServer.Submit
{
    using System;
    using System.Diagnostics;
    using System.Linq;
    using System.Windows.Forms;
    using Microsoft.TeamFoundation;
    using Properties;

    /// <summary>
    /// ShelveDelete class.
    /// </summary>
    internal partial class ShelveDelete : WizardControlTemplate
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ShelveDelete"/> class.
        /// </summary>
        public ShelveDelete()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                this.InitializeComponent();

                this.cmbTFSServer.Items.Clear();
                foreach (var item in TeamFoundationHelper.GetRegisteredCollectionNames())
                {
                    this.cmbTFSServer.Items.Add(item);
                }

                Utilities.FixComboItemsWidth(this, this.cmbTFSServer);

                if (this.cmbTFSServer.Items.Count > 0)
                {
                    Utilities.GetDefaultValue(this.cmbTFSServer, Settings.Default.TfsSourceServer);
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Update window.
        /// </summary>
        /// <param name="title">Window Title.</param>
        /// <param name="description">Window Description.</param>
        /// <param name="backButtonEnabled">Back Button Enabled?</param>
        /// <param name="nextButtonEnabled">Next Button Enabled?</param>
        /// <param name="nextButtonCaption">Next Button Caption.</param>
        /// <param name="action">Action to perform on control.</param>
        public override void UpdateWindow(Label title, RichTextBox description, out bool backButtonEnabled, out bool nextButtonEnabled, out string nextButtonCaption, object action)
        {
            backButtonEnabled = true;
            nextButtonEnabled = this.gridShelveSets.SelectedRows.Count > 0;
            nextButtonCaption = Resources.DeleteShelveButtonCaption;

            title.Text = Resources.DeleteShelveTitle;
            description.Text = Resources.DeleteShelveDescription;
        }

        /// <summary>
        /// Continue button event.
        /// </summary>
        public override void NextStep()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (!this.InternalValidate())
                {
                    return;
                }

                var result = MessageBox.Show(
                       Resources.ConfirmDeleteShelveSetsWarning,
                       Resources.WarningString,
                       MessageBoxButtons.YesNo,
                       MessageBoxIcon.Exclamation,
                       MessageBoxDefaultButton.Button2,
                       MessageBoxOptions.RightAlign & MessageBoxOptions.RtlReading);

                if (result == DialogResult.Yes)
                {
                    foreach (var row in this.gridShelveSets.Rows.Cast<DataGridViewRow>().Where(row => bool.Parse(row.Cells["colSelect"].Value.ToString())))
                    {
                        // Check if ShelveSet has a open code review going on
                        if (TfsSubmitConfig.CodeReviewEnabled)
                        {
                            foreach (var workspace in this.cmbWorkspace.Items)
                            {
                                var changeListId = MalevichDal.GetChangeListId(row.Cells["colShelveSet"].Value.ToString(), workspace.ToString());

                                // changeListId == -1 means that here is no open code review on that specific workspace for this shelve set.
                                if (changeListId == -1)
                                {
                                    continue;
                                }

                                var changeListStage = MalevichDal.GetChangeListStage(changeListId);

                                // Code Review is not closed if stage <> 2
                                if (changeListStage != 2)
                                {
                                    MalevichDal.CloseCodeReview(row.Cells["colShelveSet"].Value.ToString());
                                }
                            }
                        }

                        TeamFoundationHelper.DeleteShelvesets(this.cmbTFSServer.Text, this.cmbWorkspace.Text, row.Cells["colShelveSet"].Value.ToString());
                    }

                    MessageBox.Show(
                       Resources.ShelveSetsDeletedWarning,
                       Resources.WarningString,
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Information,
                       MessageBoxDefaultButton.Button1,
                       MessageBoxOptions.RightAlign & MessageBoxOptions.RtlReading);

                    this.FireGoHomeRequested(null /* action */);
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Select TFS Collection.
        /// </summary>
        /// <param name="sender">Object sender.</param>
        /// <param name="e">Event arguments object.</param>
        private void CmbTfsServerSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                this.cmbWorkspace.Items.Clear();

                if (this.cmbTFSServer.Text.Length == 0)
                {
                    return;
                }

                Utilities.SetDefaultValue("TfsSourceServer", this.cmbTFSServer.Text);

                // Retrieve User workspaces for specific project collection.
                foreach (var item in TeamFoundationHelper.GetWorkspaceNames(this.cmbTFSServer.Text))
                {
                    this.cmbWorkspace.Items.Add(item);
                }

                Utilities.FixComboItemsWidth(this, this.cmbWorkspace);

                if (this.cmbWorkspace.Items.Count > 0)
                {
                    Utilities.GetDefaultValue(this.cmbWorkspace, Settings.Default.TfsSourceWorkspace);
                }
            }
            catch (TeamFoundationServiceUnavailableException err)
            {
                MessageBox.Show(
                   err.Message,
                   Resources.UnhandledException,
                   MessageBoxButtons.OK,
                   MessageBoxIcon.Error,
                   MessageBoxDefaultButton.Button1,
                   MessageBoxOptions.RightAlign & MessageBoxOptions.RtlReading);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Select Workspace.
        /// </summary>
        /// <param name="sender">Object sender.</param>
        /// <param name="e">Event arguments object.</param>
        private void CmbWorkspaceSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                this.gridShelveSets.Rows.Clear();

                if (this.cmbWorkspace.Text.Length == 0)
                {
                    return;
                }

                Utilities.SetDefaultValue("TfsSourceWorkspace", this.cmbWorkspace.Text);

                var shelvesets =
                    TeamFoundationHelper.GetShelvesets(this.cmbTFSServer.Text, this.cmbWorkspace.Text).ToDictionary(
                        obj => obj.Name, obj => obj);
                foreach (var shelveset in shelvesets)
                {
                    var rowIndex = this.gridShelveSets.Rows.Add();
                    this.gridShelveSets.Rows[rowIndex].Cells["colSelect"].Value = false;
                    this.gridShelveSets.Rows[rowIndex].Cells["colShelveSet"].Value = shelveset.Value.Name;
                    this.gridShelveSets.Rows[rowIndex].Cells["colDescription"].Value = shelveset.Value.Comment;
                    this.gridShelveSets.Rows[rowIndex].Cells["colDate"].Value = shelveset.Value.CreationDate;
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Grid Header column width changed event.
        /// </summary>
        /// <param name="sender">Object sender.</param>
        /// <param name="e">Event arguments object.</param>
        private void GridFilesColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            if (e.Column == this.gridShelveSets.Columns["colSelect"])
            {
                Debug.Assert(e.Column != null, "Column should never be null");
                e.Column.Width = 50;
            }
        }

        /// <summary>
        /// Files Selection change event.
        /// </summary>
        /// <param name="sender">Object sender.</param>
        /// <param name="e">Event arguments.</param>
        private void GridFilesSelectionChanged(object sender, EventArgs e)
        {
            this.FireChangeContinueButtonEnabled(this.gridShelveSets.SelectedRows.Count > 0);
        }

        /// <summary>
        /// Header click event.
        /// </summary>
        /// <param name="sender">Object sender.</param>
        /// <param name="e">Event arguments object.</param>
        private void ChkRowsCheckedChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                // We use this code to mark/unmark all files as selected/unselected. 
                var dataGridViewColumn = this.gridShelveSets.Columns["colSelect"];
                if (dataGridViewColumn != null)
                {
                    bool selected = this.chkRows.Checked;
                    for (var index = this.gridShelveSets.Rows.Count - 1; index >= 0; index--)
                    {
                        this.gridShelveSets.Rows[index].Cells["colSelect"].Value = selected;
                    }
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// Internal Validate.
        /// </summary>
        /// <returns>False if has errors, otherwise true.</returns>
        private bool InternalValidate()
        {
            var hasFiles = this.gridShelveSets.Rows.Cast<DataGridViewRow>().Any(row => bool.Parse(row.Cells["colSelect"].Value.ToString()));
            if (!hasFiles)
            {
                MessageBox.Show(
                       Resources.NoShelveSetsSelectedToDeleteError,
                       Resources.ErrorString,
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Information,
                       MessageBoxDefaultButton.Button1,
                       MessageBoxOptions.RightAlign & MessageBoxOptions.RtlReading);
                return false;
            }

            return true;
        }
    }
}
